package demo0512;

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Scanner;

public class Test01 {
    public static void test(String fileName, String data) throws IOException {
        File file = new File(fileName);
        File directory = file.getParentFile();
        if (directory!= null &&!directory.exists()) {
            directory.mkdirs();
        }
        FileWriter fileWriter = new FileWriter(fileName);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(data);
        bufferedWriter.close();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要保存的文件名（包含路径）：");
        String fileName = scanner.nextLine();
        System.out.println("请输入要保存的数据：");
        String data = scanner.nextLine();
        try {
            test(fileName, data);
            System.out.println("数据已成功保存到文件：" + fileName);
        } catch (IOException e) {
            System.err.println("保存数据时出现错误：" + e.getMessage());
            e.printStackTrace();
        } finally {
            scanner.close();
        }
    }
}
